package com.mes.handler;

import com.basis.utils.BaseServletHandler;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.dal.service.OBDal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

//BOM上传图片
public class BomImportPhotoHandler extends BaseServletHandler {

	private String p_id;

	@Override
	protected JSONObject service(HttpServletRequest request, HttpServletResponse response) {

		p_id = "";
		p_id = request.getParameter("WmlmNameId");

		JSONObject result = new JSONObject();

		try {
			result.put("desc", "系统繁忙，请稍后再试。");
			result.put("result", false);
			request.setCharacterEncoding("utf-8");


			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 设置 缓存的大小，当上传文件的容量超过该缓存时，直接放到 暂时存储室
			factory.setSizeThreshold(1024 * 1024);
			ServletFileUpload upload = new ServletFileUpload(factory);

			// 可以上传多个文件
			List<FileItem> listItem = (List<FileItem>) upload.parseRequest(request);
			for (FileItem item : listItem) {
				if (item.getName() == null || "".equals(item.getName().trim())) {
					// 不含文件内容
					continue;
				}

				//String savePath = request.getSession().getServletContext().getRealPath("/upload");
				String  savePath = "D:\\JavaTool\\BomPhoto";
				File file = new File(savePath);


				if (!file.exists() && !file.isDirectory()) {
					//创建目录
					file.mkdir();
				}

				String name =  item.getFieldName();

				String fileName =  item.getName();


				if(fileName.endsWith(".pdf") || fileName.endsWith(".png") || fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")){
					fileName = fileName.substring(fileName.lastIndexOf("\\")+1);

					InputStream in = item.getInputStream();

					//EmesPBomItemShape updatas = OBDal.getInstance().get(EmesPBomItemShape.class, p_id);

					/*//判断该用户是否已经上传，如果已经上传就删除原上传的pdf文件
					if("fileName".equals(name)) {
						if(updatas.getPostion() != null){
							File f = new File(updatas.getPostion());
							f.delete();
						}
					} else if("cards".equals(name)){
						if(updatas.getFilePath() != null){
							File f = new File(updatas.getFilePath());
							f.delete();
						}
					}*/

					//时间戳
					long Pix = System.currentTimeMillis();
					String filePix = Pix + "";

					String oldPix = fileName.substring(fileName.lastIndexOf("."),fileName.length());
					fileName = fileName.substring(0,fileName.lastIndexOf("."));
					fileName = fileName + filePix + oldPix;
					FileOutputStream out = new FileOutputStream(savePath+ "\\" + fileName);

					//创建一个缓冲区
					byte buffer[] = new byte[1024];
					//判断输入流中的数据是否已经读完的标识
					int len = 0;
					//循环将输入流读入到缓冲区当中，(len=in.read(buffer))>0就表示in里面还有数据
					while((len=in.read(buffer))>0){
						//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
						out.write(buffer, 0, len);
					}
					//关闭输入流
					in.close();
					//关闭输出流
					out.close();

					//updatas.set("filename", item.getName());


					if(name.equals("fileName")){
						String sql = "UPDATE Emes_PBom_Item_Shape set file_path = '"+savePath + "\\" + fileName+"'  where emes_pbom_item_shape_id = '"+p_id+"' ";

						OBDal.getInstance().getSession().createSQLQuery(sql).executeUpdate();

					//	updatas.setFilePath(savePath + "\\" + fileName);

					}else if(name.equals("cards") ){

						String eql = "UPDATE Emes_PBom_Item_Shape  set data_file_path = '"+savePath + "\\" + fileName+"'  where emes_pbom_item_shape_id = '"+p_id+"' ";

						OBDal.getInstance().getSession().createSQLQuery(eql).executeUpdate();

						//updatas.setDataFilePath(savePath + "\\" + fileName);
					}

				//	OBDal.getInstance().save(updatas);
				}else{
					result.put("desc", "只允许图片格式的文件上传！");
					result.put("result", false);
					return result;

				}
			}
			result.put("desc", "上传成功！");
			result.put("result", true);

			OBDal.getInstance().commitAndClose();
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();
		}
		return result;
	}


}
	
